<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
	<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
	<meta name="apple-mobile-web-app-capable" content="yes"/>
	<title>MVC Repeat with Selectable RoundRectList - Multiple Select</title>

	<script type="text/javascript" src="../../../../dojox/mobile/deviceTheme.js" data-dojo-config="mblThemeFiles: ['base']"></script>

	<!-- required: dojo.js -->
	<script type="text/javascript" src="../../../../dojo/dojo.js"
		data-dojo-config="isDebug: true, async: true, parseOnLoad: false, mvc: {debugBindings: true}"></script>

	<script type="text/javascript">
		require([
			"dojo/_base/lang",
			"dojo/_base/declare",
			"dojo/_base/connect",
			"dijit/registry",
			"dojo/dom",
			"dojox/mobile/parser",
			"dojo/store/Memory",
			"dojo/ready",
			"dojo/when",
			"dojo/Stateful",
			"dojox/mvc/getStateful",
			"dojo/data/ItemFileWriteStore",
			"dojo/store/Memory",
			"dojox/mvc/EditStoreRefController",
			"dojox/mvc/ListController",
			"dojox/mvc/at",
			"dojox/mvc/Group",
			"dojox/mvc/WidgetList",
			"dojox/mvc/Templated",
			"dojox/mvc/_InlineTemplateMixin",
			"dojox/mvc/Output",
			"dojox/mobile",
			"dojox/mobile/compat",
			"dojox/mobile/FixedSplitter",
			"dojox/mobile/Container",
			"dojox/mobile/ListItem",
			"dojox/mobile/Button",
			"dojox/mobile/ToolBarButton",
			"dojox/mobile/TextBox",
			"dojox/mobile/CheckBox",
			"dojox/mobile/EdgeToEdgeDataList",
			"dojox/mobile/View",
			"dojox/mobile/ScrollableView",
			"dojox/mobile/SimpleDialog",
			"dojox/mobile/Heading",
			"dojox/mobile/deviceTheme"
		], function(lang, declare, connect, registry, dom, parser, MemoryStore, ready, when, Stateful, getStateful, ItemFileWriteStore, Memory, EditStoreRefController, ListController, at){
			window.at = at;

			function _addNewItem(e){
				console.log("_addNewItem called");

				var datamodel = currentctrl;
				var parentId;
				try{
					parentId = datamodel.model[0].parentId;
				}catch (e){
					console.log("Warning: itemlistmodel is empty, get parentId from listsmodel");
					parentId = app.loadedModels.listsmodel[window.selected_configuration_item].id;
				}

				var index = datamodel.model.length;
				var insert = new Stateful({
					"id": (new Date().getTime()),
					"parentId": parentId,
					"title": "",
					"notes": "To do",
					"due": "2010-10-15T11:03:47.681Z",
					"completionDate": "",
					"reminder": "2010-10-15T11:03:47.681Z",
					"repeat": 0,
					"priority": 0,
					"hidden": false,
					"completed": false,
					"deleted": false
				});
				datamodel.model.push(insert);
				datamodel.commit(); //need to commit after delete. TODO: need to enhance the performance
				var r = registry.byId("todomain");
				r.performTransition("details", 1, "none");
				movedTo(index);
				//update cache
				//app.loadedModels.itemlistsmodel[parentId] = datamodel.model;
				//refresh view
				//window.showData(datamodel.model);
			}

			completeConverter = {
				format: function(value){
					console.log("****in completeConverter format value = "+value);
					//return "dijitMenuItemLabel" + (value ? " complete" : "");
					//ctrl.set("completed", false);
					//ctrlComplete.set("completed", true);
					//for(var a = this.source.inModel, i = 0; i < a.length; i++){
					//	if(a[i].id == this.target.id){
							console.log("****in completeConverter format this.source.id = "+this.source.id);
							console.log(this.source);
							//return a[i];
					//	}
					//}
					return value;
				},
				parse: function(value){
					console.log("****in completeConverter parse value = "+value);
					console.log("****in completeConverter parse this.source.id = "+this.source.id);
					console.log(this.source);
					var model = ctrlComplete.model;
					if(value){
						model = currentctrl.model;
					}
					for(var a = model, i = 0; i < a.length; i++){
						if(a[i].id == this.source.id){
							if(value){ // remove from list and move to completed
								window.setTimeout(lang.hitch(window, moveToComplete, currentctrl.model, ctrlComplete.model, i, value), 500);
							}else{
								window.setTimeout(lang.hitch(window, moveFromComplete, ctrlComplete.model, currentctrl.model, i, value), 500);
							}
						}
					}
					//throw new Error(); // Stop copying the new value for unchecked case
					if(!value){ throw new Error(); } // Stop copying the new value for unchecked case
					return value;
				}
			};

			var listData = {
				"identifier": "id",
				"items": [
					{
						"id": 100,
						"parentId":1,
						"title": "item 1 to do for 1",
						"notes": "To do",
						"due": "2010-10-15T11:03:47.681Z",
						"completionDate": "",
						"reminder": "2010-10-15T11:03:47.681Z",
						"repeat": 0,
						"priority": 0,
						"hidden": false,
						"completed": false,
						"deleted": false
					},
					{
						"id": 103,
						"parentId":1,
						"title": "item 3 to do for 1",
						"notes": "To do",
						"due": "2010-10-15T11:03:47.681Z",
						"completionDate": "",
						"reminder": "2010-10-15T11:03:47.681Z",
						"repeat": 2,
						"priority": 2,
						"hidden": false,
						"completed": false,
						"deleted": false
					}
				]
			};

			var listData1 = {
				"identifier": "id",
				"items": [
					{
						"id": 101,
						"parentId":2,
						"title": "item 1 to do for 2",
						"notes": "To do",
						"priority": 0,
						"due": "2010-10-15T11:03:47.681Z",
						"completionDate": "",
						"reminder": "2010-10-15T11:03:47.681Z",
						"repeat": 0,
						"hidden": false,
						"completed": false,
						"deleted": false
					},
					{
						"id": 103,
						"parentId":2,
						"title": "item 3 else to do for 2",
						"notes": "To do",
						"priority": 0,
						"due": "2010-10-15T11:03:47.681Z",
						"completionDate": "",
						"reminder": "2010-10-15T11:03:47.681Z",
						"repeat": 0,
						"hidden": false,
						"completed": false,
						"deleted": false
					}
				]
			};

			var completedListData = {
				"identifier": "id",
				"items": [
					{
						"id": 102,
						"parentId":2,
						"title": "item 2 to do for 0",
						"notes": "To do",
						"due": "2010-10-15T11:03:47.681Z",
						"completionDate": "",
						"reminder": "2010-10-15T11:03:47.681Z",
						"repeat": 0,
						"priority": 1,
						"hidden": false,
						"completed": true,
						"deleted": false
					}
				]
			};

			var allListsData = {
				"identifier": "id",
				"items": [
					{
						"title":"Reminders",
						"id":0,
						"parentId":null,
						"itemsurl":"../resources/data/items-for-0.json"
					},
					{
						"title":"Work Items",
						"id":1,
						"parentId":null,
						"itemsurl":"../resources/data/items-for-1.json"
					}
				]
			};

			var inited,
			ctrlClass = declare([EditStoreRefController, ListController], {
				cursorIndex: 0,
				completed: "",
				completedTyped: "",
				_refModelProp: "model",

				addEmpty: function(){
					this.model.push(new Stateful({First: "", Last: "", Location: "", Office: "", Email: "", Tel: "", Fax: ""}));
					this.set("cursorIndex", this.get("length") - 1);
				},

				remove: function(idx){
					this.model.splice(idx, 1);
					if(this.get("cursorIndex") < 0){
						this.set("cursorIndex", this.get("length") - 1);
					}
				},

				_setCompletedAttr: function(value){
					this.set("completedTyped", value);
					console.log("_setCompletedAttr called for completedTyped="+this.completedTyped +" with value="+value);

					when(this.queryStore(), function(){
						if(inited){
							parser.parse();
							//inited = true;
							var d = registry.byId("addbutton");
							connect.connect(d, "onClick", this, _addNewItem);
						}
					});
					this._set("completed", value);
				}
			});
			ctrlListsClass = declare([EditStoreRefController, ListController], {
				cursorIndex: 0,
				_refModelProp: "model"
			});

			listsCtrls = [];
			ctrlComplete = new ctrlClass({store: new Memory({data: completedListData})});
			listsCtrls.push(ctrlComplete);
			currentctrl = new ctrlClass({store: new Memory({data: listData})});
			listsCtrls.push(currentctrl);
			ctrl1 = new ctrlClass({store: new Memory({data: listData1})});
			listsCtrls.push(ctrl1);

			listsCtrl = new ctrlListsClass({store: new Memory({data: allListsData})});
			when(listsCtrl.queryStore(), function(){
				listsCtrls[0].set("completed", true);
				//currentctrl.set("completed", false);
				listsCtrls[1].set("completed", false);
				inited = true;
				listsCtrls[2].set("completed", false);
			});

			// called when showing item details
			movedTo = function(index) {
				console.log("movedTo called with index"+index);
				currentctrl.set('cursorIndex', index);
				var g = registry.byId("detailsGroup");
				g.set("target", at(currentctrl, 'cursor'));
				var h = registry.byId("detailsHeading");
				h.set("label","To-Do Details");
				var h2 = dom.byId("detailsHeading2");
				h2.innerHTML="To Do Item";
			};

			// called when showing item details for a completed item
			movedToCompleted = function(index) {
				console.log("movedToCompleted called with index"+index);
				ctrlComplete.set('cursorIndex', index);
				var g = registry.byId("detailsGroup");
				g.set("target", at(ctrlComplete, 'cursor'));
				var h = registry.byId("detailsHeading");
				h.set("label","Completed To-Do");
				var h2 = dom.byId("detailsHeading2");
				h2.innerHTML="Completed Item";
			};

			// called when an item is completed
			moveToComplete = function(fromModel, toModel, i, value) {
				console.log("****in moveToComplete value = "+value);
				var t = fromModel.splice(i, 1);
				t[0].set("completed", value);
				toModel.push(t[0]);
			};

			// called when a completed items is unchecked
			moveFromComplete = function(fromModel, toModel, i, value) {
				console.log("****in moveFromComplete value = "+value);
				var t = fromModel.splice(i, 1);
				t[0].set("completed", value);
				toModel = listsCtrls[t[0].get('parentId')].model;
				toModel.push(t[0]);
			};

			// called when a different list is selected
			selectList = function(index) {
				if(index != -1){
					index = parseInt(index)+1;
				}else{
					index = '0';
				}
				console.log("selectList called with index"+index);
				listsCtrl.set('cursorIndex', index);
				//listsCtrl.set('cursorIndex', index);//listItems
				var r = registry.byId("listItems");
				currentctrl = listsCtrls[index];
				r.set("children", at(currentctrl, 'model'));
			};

			// called to delete the selected item
			deleteSelected = function() {
				console.log("deleteSelected called with currentctrl.cursorIndex="+currentctrl.cursorIndex);
				console.log("deleteSelected called with currentctrl.cursor.title="+currentctrl.cursor.title);
				currentctrl.model.splice(currentctrl.cursorIndex, 1);
				var r = registry.byId("details");
				r.performTransition("todomain", 1, "none");
			};

			showDlg = function(dlg){
				registry.byId(dlg).show();
			};

			hideDlg = function(dlg){
				registry.byId(dlg).hide();
			};

			resetAll = function() {
				console.log("resetAll called");
			};
		});

	</script>
</head>
<body style="visibility:hidden;">
	<div data-dojo-type="dojox.mobile.FixedSplitter" data-dojo-props='orientation:"H"'>
		<div data-dojo-type="dojox.mobile.Container" style="width:300px;border-right:1px solid black;">
			<div id="settings" data-dojo-type="dojox.mobile.ScrollableView">
			<!--  <h1 data-dojo-type="dojox.mobile.Heading" data-dojo-props='fixed:"top"'>Configure</h1> -->
			<h2 data-dojo-type="dojox.mobile.Heading" region="top">
				Configure
				<img style="position: absolute; display: block; width: 32px; height: 32px; right: 0; top: 0" onClick="editConfiguration();" src="../images/settings.png">
			</h2>
 			<ul data-dojo-type="dojox.mobile.RoundRectList">
				<li data-dojo-type="dojox.mobile.ListItem"  clickable="true"
				data-dojo-props="onClick: function(){console.log('selected list ', '-1'); selectList('-1');}">
					Completed
				</li>
			</ul>
			<ul data-dojo-type="dojox/mobile/RoundRectList"
				data-dojo-mixins="dojox/mvc/WidgetList,dojox/mvc/_InlineTemplateMixin"
				data-dojo-props="children: at(listsCtrl, 'model')"
				data-mvc-child-type="dojox/mvc/Templated"
				data-mvc-child-mixins="dojox/mobile/ListItem"
				data-mvc-child-props="clickable: true,
				                      onClick: function(){ console.log('Selected list: ' + this.indexAtStartup); selectList(this.indexAtStartup); }">
				<script type="dojox/mvc/InlineTemplate">
					<li class="mblVariableHeight">
						<div class="mblListItemLabel" style="display: block;" data-dojo-type="dojox/mvc/Output" data-dojo-props="value: at('rel:', 'title')"></div>
					</li>
				</script>
			</ul>
		</div>
	</div>
	<div data-dojo-type="dojox.mobile.Container">
		<div id="main">
			<div id="leftNav"></div>
			<div id="mainContent">
				<div id="todomain" data-dojo-type="dojox.mobile.View" selected="true">
					<div data-dojo-type="dojox.mvc.Group"
						data-dojo-props="target: at(listsCtrl, 'cursor')">
						<div data-dojo-type="dojox.mobile.Heading" region="top"
							data-dojo-props="label: at('rel:','title')">
							<span id="addbutton"  data-dojo-type="dojox.mobile.ToolBarButton"
									data-dojo-props='icon:"mblDomButtonWhitePlus"' style="float:right;"
									onclick="console.log('+ was clicked')"></span>
						</div>
					</div>
					<ul id="listItems"
						data-dojo-type="dojox/mobile/RoundRectList"
						data-dojo-mixins="dojox/mvc/WidgetList,dojox/mvc/_InlineTemplateMixin"
						data-dojo-props="children: at(currentctrl, 'model')"
						data-mvc-child-type="dojox/mvc/Templated"
						data-mvc-child-mixins="dojox/mobile/ListItem"
						data-mvc-child-props="moveTo: 'details',
						                      clickable: true,
						                      transitionOptions: {title: 'Detail', target: 'details,detail'},
						                      callback: function(){ movedTo(this.indexAtStartup); },
						                      onClick: function(){ console.log('Select item : ' + this.indexAtStartup); window.selected_item = this.indexAtStartup; }">
						<script type="dojox/mvc/InlineTemplate">
							<li class="mblVariableHeight">
								<table>
									<tr>
										<td>
											<input preventTouch='true' type='checkbox'
												data-dojo-type="dojox.mobile.CheckBox"
												data-dojo-props="checked: at('rel:', 'completed').transform(completeConverter)"/></td>
										<td data-dojo-type="dojox.mvc.Output" data-dojo-props="value: at('rel:', 'title')"></td>
									</tr>
								</table>
							</li>
						</script>
					</ul>
				</div>
				<div id="details" data-dojo-type="dojox.mobile.ScrollableView">
					<h1 id="detailsHeading" data-dojo-type="dojox.mobile.Heading" back="Back" moveTo="todomain">To-Do Details</h1>
					<div id="detailsGroup" class="fieldset" data-dojo-type="dojox.mvc.Group" data-dojo-props="target: at(currentctrl, 'cursor')">
						<h2 id="detailsHeading2">Completed Items</h2>
						<div class="field-row">
							<span>To Do</span>
							<input id="todo" data-dojo-type="dojox.mobile.TextBox"
								placeholder="To do placeholder"
								data-dojo-props="value: at('rel:', 'title')"/>
						</div>
						<ul data-dojo-type="dojox.mobile.RoundRectList">
							<li data-dojo-type="dojox.mobile.ListItem"
								data-dojo-props="clickable: true,
								                 noArrow: true,
								                 onClick: function(){ console.log('delete item'); showDlg('dlg_confirm'); }">
								Delete
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>
		<div id="dlg_confirm" data-dojo-type="dojox.mobile.SimpleDialog">
			<div class="mblSimpleDialogTitle">Delete Confirmation</div>
			<div class="mblSimpleDialogText">Are you sure you want to delete this item?</div>
			<button data-dojo-type="dojox.mobile.Button" class="mblSimpleDialogButton" onclick="hideDlg('dlg_confirm')">No</button>
			<button data-dojo-type="dojox.mobile.Button" class="mblSimpleDialogButton mblBlueButton" onclick="hideDlg('dlg_confirm'); deleteSelected();">Yes</button>
		</div>
	</div>
</body>
</html>
